package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.base.exception.EamException;
import com.uinnova.product.eam.comm.exception.BusinessException;
import com.uinnova.product.eam.comm.model.es.EamCategory;
import com.uinnova.product.eam.comm.model.es.EamDiagramRelationSys;
import com.uinnova.product.eam.model.DiagramBo;
import com.uinnova.product.eam.model.PlanDiagramRequest;
import com.uinnova.product.eam.model.dto.EamCategoryDTO;
import com.uinnova.product.eam.model.enums.ArtifactEnum;
import com.uinnova.product.eam.model.vo.RelateDiagram;
import com.uinnova.product.eam.model.vo.RelateionDiagramVo;
import com.uinnova.product.eam.service.ESDiagramSvc;
import com.uinnova.product.eam.service.EamCategorySvc;
import com.uinnova.product.eam.service.es.EamDiagramRelationSysDao;
import com.uinnova.project.base.diagram.comm.diagram.DiagramShareRecord;
import com.uinnova.project.base.diagram.comm.diagram.EamDiagramQuery;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.db.eam.*;
import com.uinnova.project.service.eam.ESShareDiagramSvc;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Deprecated
public class IamsESDiagramSvcImpl implements ESDiagramSvc {

    @Value("${http.resource.space}")
    private String httpResouceUrl;

    @Autowired
    private ESDiagramDao esDiagramDao;

    @Autowired
    private ESShareDiagramSvc esShareDiagramSvc;

    @Autowired
    private IUserApiSvc userApiSvc;

    @Autowired
    private ESDiagramSheetDao iamsEsDiagramSheetDao;

    @Autowired
    private ESDiagramNodeDao iamsEsDiagramNodeDao;

    @Autowired
    private ESDiagramLinkDao iamsEsDiagramLinkDao;

    @Resource
    private EamDiagramRelationSysDao eamDiagramRelationSysDao;

    @Resource
    private ESShareDiagramDao esShareDiagramDao;

    @Autowired
    private EamCategorySvc categorySvc;

    private Map<Long, SysUser> queryUserList(Set<Long> creatorIdSet) {
        CSysUser cSysUser = new CSysUser();
        cSysUser.setDomainId(1L);
        cSysUser.setIds(creatorIdSet.toArray(new Long[]{}));
        cSysUser.setSuperUserFlags(new Integer[]{0, 1});
        List<SysUser> creatorList = userApiSvc.getSysUserByCdt(cSysUser);
        Map<Long, SysUser> userIdObjMap = new HashMap<>();
        creatorList.forEach(
                creator -> {
                    creator.setLoginPasswd(null);
                    userIdObjMap.put(creator.getId(), creator);
                    String icon = creator.getIcon();
                    // 这儿判断是因为当前用户是同一个对象，所以再修改会无限拼接，勿删！！！！！！
                    if (icon != null && !icon.startsWith(this.httpResouceUrl)) {
                        creator.setIcon(httpResouceUrl + icon);
                    }
                }
        );
        return userIdObjMap;
    }

    private ESDiagram judgeAllSingleDiagramAuth(Long diagramId, String type) {
        SysUser currentUserInfo = SysUtil.getCurrentUserInfo();
        Long userId = currentUserInfo.getId();
        Long domainId = currentUserInfo.getDomainId();
        //1.不限制userId进行查询
        EamDiagramQuery diagramQuery = new EamDiagramQuery();
        diagramQuery.setId(diagramId);
        diagramQuery.setStatus(1);
        diagramQuery.setDataStatus(1);
        diagramQuery.setDomainId(domainId);
        if (!BinaryUtils.isEmpty(type) && "version".equals(type)) {
            diagramQuery.setHistoryVersionFlag(0);
        }else if (!BinaryUtils.isEmpty(type) && "REC_ATT_DATA".equals(type)) {
            List<ESDiagram> recAndAttData = esDiagramDao.getListByCdt(diagramQuery);
            if (CollectionUtils.isEmpty(recAndAttData)) {
                return null;
            } else {
                return recAndAttData.get(0);
            }
        } else {
            diagramQuery.setHistoryVersionFlag(1);
        }
        List<ESDiagram> diagramList = esDiagramDao.getListByCdt(diagramQuery);
        //2.查不出，视图不存在，报错
        if (BinaryUtils.isEmpty(diagramList)) {
            throw new EamException("操作视图不存在，请核对视图当前信息");
        }
        //3.查出来，判断其是否具有视图权限
        ESDiagram esDiagram = diagramList.get(0);
        return esDiagram;
    }

    @Override
    public void writeReleaseDiagramId(String releaseDiagramId, Long id) {
        StringBuffer script = new StringBuffer(1000);
        script.append("ctx._source.releaseDiagramId=params.releaseDiagramId;");
        Map<String, Object> params = new HashMap<>();
        params.put("releaseDiagramId", releaseDiagramId);
        esDiagramDao.updateByQuery(QueryBuilders.termQuery("id", id), script.toString(), true, params);
    }

    @Override
    public int increaseReleaseVersionByDEnergyId(String dEnergyId) {
        return esDiagramDao.increaseReleaseVersionByDEnergyId(dEnergyId);
    }

    @Override
    public void writeHistoryVersion(Long diagramId) {
        StringBuffer script = new StringBuffer(1000);
        script.append("ctx._source.historyVersionFlag=params.historyVersionFlag;");
        Map<String, Object> params = new HashMap<>();
        params.put("historyVersionFlag", 0);
        esDiagramDao.updateByQuery(QueryBuilders.termQuery("id", diagramId), script.toString(), true, params);
    }

    @Override
    public int setLocalVersionByDEnergyIdToZero(Long diagramId) {
        StringBuffer script = new StringBuffer(1000);
        script.append("ctx._source.localVersion=params.localVersion;");
        Map<String, Object> params = new HashMap<>();
        params.put("localVersion", 0);
        boolean suc = esDiagramDao.updateByQuery(QueryBuilders.termQuery("id", diagramId), script.toString(), true,
                params);
        return suc ? 1 : 0;
    }

    /**
     * 名称模糊分页查询已发布的视图
     *
     * @param request {@link PlanDiagramRequest}
     * @return 数据对象 {@link ESDiagram}
     */
    @Override
    public Page<ESDiagram> findDiagramLikeName(PlanDiagramRequest request) {
        TermQueryBuilder dataStatus = QueryBuilders.termQuery("dataStatus", 1);
        TermQueryBuilder status = QueryBuilders.termQuery("status", 1);
        TermQueryBuilder creatorKeyWord = QueryBuilders.termQuery("creator.keyword",
                SysUtil.getCurrentUserInfo().getLoginCode());
        TermQueryBuilder historyVersionFlag = QueryBuilders.termQuery("historyVersionFlag", 1);
        TermQueryBuilder isOpen = QueryBuilders.termQuery("isOpen", 0);

        BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder mustQuery = QueryBuilders.boolQuery()
                .must(dataStatus)
                .must(historyVersionFlag)
                .must(creatorKeyWord)
                .must(isOpen)
                .must(status);

        if(request.getViewTypes() != null && request.getViewTypes().size() >=1){
            TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("viewType.keyword", request.getViewTypes());
            mustQuery.must(termsQueryBuilder);
        }

        if (!org.apache.commons.lang3.StringUtils.isBlank(request.getViewType())) {
            TermQueryBuilder viewTypeKeyWord = QueryBuilders.termQuery("viewType.keyword", request.getViewType());
            mustQuery.must(viewTypeKeyWord);
        }

        if (!BinaryUtils.isEmpty(request.getDiagramName())) {
            MultiMatchQueryBuilder name = QueryBuilders.multiMatchQuery(request.getDiagramName(), "name")
                    .operator(Operator.AND).type(MultiMatchQueryBuilder.Type.PHRASE_PREFIX).lenient(true);
            mustQuery.must(name);
        }

        List<String> diagramEnergyList = findSysDiagramEnergyList(request.getSysCiCodeList());
        if (!BinaryUtils.isEmpty(diagramEnergyList)) {
            shouldQuery.should(QueryBuilders.termsQuery("dEnergy.keyword", diagramEnergyList));
        }

        // 自由视图
        BoolQueryBuilder freeDiagramQuery = null;
        if (request.getViewTypes().contains(String.valueOf(ArtifactEnum.FREEDOM_DIAGRAM.getArtifactType()))) {
            freeDiagramQuery = QueryBuilders.boolQuery()
                    .must(dataStatus)
                    .must(historyVersionFlag)
                    .must(creatorKeyWord)
                    .must(isOpen)
                    .must(status)
                    .mustNot(QueryBuilders.existsQuery("viewType"));
        }

        if (!BinaryUtils.isEmpty(request.getDirType())) {
            TermQueryBuilder dirType = QueryBuilders.termQuery("dirType", request.getDirType());
            mustQuery.must(dirType);
            if (freeDiagramQuery != null) {
                freeDiagramQuery.must(dirType);
            }
        }

        BoolQueryBuilder mainQuery = QueryBuilders.boolQuery();

        BoolQueryBuilder query = QueryBuilders.boolQuery()
                .must(mustQuery)
                .must(shouldQuery);

        QueryBuilder shareQuery = shareQuery(request);
        if (shareQuery != null) {
            mainQuery.should(shareQuery);
        }

        mainQuery.should(query);
        if (freeDiagramQuery != null) {
            mainQuery.should(freeDiagramQuery);
        }
        return esDiagramDao.getSortListByQuery(request.getPageNum(), request.getPageSize(), mainQuery, "createTime",
                false);
    }

    @Override
    public Page<DiagramBo> findDiagramList(PlanDiagramRequest request) {
        List<DiagramBo> result = new ArrayList<>();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("dataStatus", 1));
        queryBuilder.must(QueryBuilders.termQuery("status", 1));
        queryBuilder.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        // 通过制品类型筛选
        if (!StringUtils.isEmpty(request.getViewType())) {
            if (Objects.equals(request.getViewType(), "0")) {
                queryBuilder.mustNot(QueryBuilders.existsQuery("viewType"));
            } else if (!Objects.equals(request.getViewType(), "1")) {
                queryBuilder.must(QueryBuilders.termQuery("viewType.keyword", request.getViewType()));
            }
        } else {
            throw new BusinessException("制品类型不能为空!");
        }

        // 通过所属领域筛选dirType
        if (!StringUtils.isEmpty(request.getDirType())) {
            queryBuilder.must(QueryBuilders.termQuery("dirType", request.getDirType()));
        }

        // 这块处理一下不查询模板类型的视图
        queryBuilder.must(QueryBuilders.termsQuery("diagramType",Arrays.asList(1,2)));

        // 通过名称筛选diagramName
        if (!StringUtils.isEmpty(request.getDiagramName())) {
            queryBuilder.must(QueryBuilders.multiMatchQuery(request.getDiagramName(), "name")
                    .operator(Operator.AND).type(MultiMatchQueryBuilder.Type.PHRASE_PREFIX).lenient(true));
        }

        if (request.getLocation() != null) {
            if (Objects.equals(request.getLocation(), 0)) {
                BoolQueryBuilder shareQueryBuilder = QueryBuilders.boolQuery();
                shareQueryBuilder.must(QueryBuilders.termQuery("sharedUserId", request.getCurrentUserId()));
                if (!StringUtils.isEmpty(request.getDirType())) {
                    shareQueryBuilder.must(QueryBuilders.termQuery("dirType", request.getDirType()));
                }
                List<DiagramShareRecord> shareRecordList = esShareDiagramDao.getListByQuery(shareQueryBuilder);

                BoolQueryBuilder orQueryBuilder = QueryBuilders.boolQuery();
                orQueryBuilder.should(QueryBuilders.termQuery("creator.keyword", request.getCurrentLoginCode()));
                if (!CollectionUtils.isEmpty(shareRecordList)) {
                    List<Long> diagramIds = shareRecordList.stream().map(shareRecord -> shareRecord.getDiagramId()).collect(Collectors.toList());
                    orQueryBuilder.should(QueryBuilders.termsQuery("id", diagramIds));
                }
                queryBuilder.must(orQueryBuilder);
                queryBuilder.must(QueryBuilders.termQuery("isOpen", request.getLocation()));
                Page<DiagramBo> diagramBoPage = handleOwner(request, queryBuilder);
                if (diagramBoPage != null) {
                    return diagramBoPage;
                }
            } else {
                queryBuilder.must(QueryBuilders.termQuery("isOpen", request.getLocation()));
                Page<DiagramBo> diagramBoPage = handleOwner(request, queryBuilder);
                if (diagramBoPage != null) {
                    return diagramBoPage;
                }
            }
        } else {
            if (request.getOwner() != null) {
                Page<DiagramBo> diagramBoPage = handleOwner(request, queryBuilder);
                if (diagramBoPage != null) {
                    return diagramBoPage;
                }
            } else {
                BoolQueryBuilder shareQueryBuilder = QueryBuilders.boolQuery();
                shareQueryBuilder.must(QueryBuilders.termQuery("sharedUserId", request.getCurrentUserId()));
                if (!StringUtils.isEmpty(request.getDirType())) {
                    shareQueryBuilder.must(QueryBuilders.termQuery("dirType", request.getDirType()));
                }
                List<DiagramShareRecord> shareRecordList = esShareDiagramDao.getListByQuery(shareQueryBuilder);

                BoolQueryBuilder orQueryBuilder = QueryBuilders.boolQuery();
                orQueryBuilder.should(QueryBuilders.termQuery("creator.keyword", request.getCurrentLoginCode()));

                BoolQueryBuilder builder = QueryBuilders.boolQuery();
                builder.mustNot(QueryBuilders.termQuery("creator.keyword", request.getCurrentLoginCode()));
                builder.must(QueryBuilders.termQuery("isOpen", 1));
                long count = esDiagramDao.countByCondition(builder);
                Page<ESDiagram> page = esDiagramDao.getListByQuery(1, (int)count, builder);
                List<ESDiagram> diagramList = new ArrayList<>();
                if (page != null && !CollectionUtils.isEmpty(page.getData())) {
                    diagramList = page.getData();
                }
                if (!CollectionUtils.isEmpty(diagramList)) {
                    Set<Long> collect = diagramList.stream().map(diagram -> diagram.getId()).collect(Collectors.toSet());
                    if (!CollectionUtils.isEmpty(shareRecordList)) {
                        Set<Long> shares = shareRecordList.stream().map(shareRecord -> shareRecord.getDiagramId()).collect(Collectors.toSet());
                        collect.addAll(shares);
                    }
                    orQueryBuilder.should(QueryBuilders.termsQuery("id", collect));
                } else {
                    if (!CollectionUtils.isEmpty(shareRecordList)) {
                        Set<Long> shares = shareRecordList.stream().map(shareRecord -> shareRecord.getDiagramId()).collect(Collectors.toSet());
                        orQueryBuilder.should(QueryBuilders.termsQuery("id", shares));
                    }
                }
                queryBuilder.must(orQueryBuilder);
            }
        }

        Page<ESDiagram> pageData = esDiagramDao.getSortListByQuery(request.getPageNum(), request.getPageSize(), queryBuilder, "createTime", false);
        List<ESDiagram> data = pageData.getData();
        if (null != data && data.size() > 0) {
            // 过滤掉业务架构-流程建模和数据架构根路径的图
            /*data = data.stream().filter(diagram -> !((Objects.equals(diagram.getDirType(), Integer.valueOf(DiagramFieldEnum.PROCESS_MODEL.getSign()))
                    || Objects.equals(diagram.getDirType(), Integer.valueOf(DiagramFieldEnum.DATA_BUILD.getSign())))
                    && Objects.equals(diagram.getDirId(), 0L))).collect(Collectors.toList());*/
            Map<String, SysUser> diagramCreatorMap = new HashMap<>();
            List<String> userLoginCodes = data.stream().map(ESDiagram::getCreator).distinct().collect(Collectors.toList());
            CSysUser cSysUser = new CSysUser();
            cSysUser.setDomainId(1l);
            cSysUser.setLoginCodes(userLoginCodes.toArray(new String[]{}));
            cSysUser.setSuperUserFlags(new Integer[]{0, 1});
            List<SysUser> creatorList = userApiSvc.getSysUserByCdt(cSysUser);
            creatorList.forEach(
                    creator -> {
                        creator.setLoginPasswd(null);
                        diagramCreatorMap.put(creator.getLoginCode(), creator);
                    }
            );
            for (ESDiagram diagramInfo : data) {
                DiagramBo diagramBo = new DiagramBo();
                diagramBo.setDiagram(diagramInfo);
                diagramBo.setCreator(diagramCreatorMap.get(diagramInfo.getCreator()));
                result.add(diagramBo);
            }
        }
        return new Page<DiagramBo>(pageData.getPageNum(), pageData.getPageSize(), pageData.getTotalRows(), pageData.getTotalPages(), result);
    }

    private Page<DiagramBo> handleOwner(PlanDiagramRequest request, BoolQueryBuilder queryBuilder) {
        if (request.getOwner() != null) {
            if (Objects.equals(request.getOwner(), 1)) {
                queryBuilder.must(QueryBuilders.termQuery("creator.keyword", request.getCurrentLoginCode()));
            } else if (Objects.equals(request.getOwner(), 2) || Objects.equals(request.getOwner(), 3)) {
                BoolQueryBuilder shareQueryBuilder = QueryBuilders.boolQuery();
                shareQueryBuilder.must(QueryBuilders.termQuery("sharedUserId", request.getCurrentUserId()));
                if (!StringUtils.isEmpty(request.getDirType())) {
                    shareQueryBuilder.must(QueryBuilders.termQuery("dirType", request.getDirType()));
                }
                List<DiagramShareRecord> shareRecordList = esShareDiagramDao.getListByQuery(shareQueryBuilder);
                if (Objects.equals(request.getOwner(), 2)) {
                    if (CollectionUtils.isEmpty(shareRecordList)) {
                        return new Page<DiagramBo>(request.getPageNum(), request.getPageSize(), 0, 0, Collections.emptyList());
                    }
                    List<Long> diagramIds = shareRecordList.stream().map(shareRecord -> shareRecord.getDiagramId()).collect(Collectors.toList());
                    queryBuilder.must(QueryBuilders.termsQuery("id", diagramIds));
                } else if (Objects.equals(request.getOwner(), 3)) {
                    if (request.getLocation() != null && request.getLocation() == 0) {
                        return new Page<DiagramBo>(request.getPageNum(), request.getPageSize(), 0, 0, Collections.emptyList());
                    }
                    queryBuilder.mustNot(QueryBuilders.termQuery("creator.keyword", request.getCurrentLoginCode()));
                    if (!CollectionUtils.isEmpty(shareRecordList)) {
                        List<Long> diagramIds = shareRecordList.stream().map(shareRecord -> shareRecord.getDiagramId()).collect(Collectors.toList());
                        queryBuilder.mustNot(QueryBuilders.termsQuery("id", diagramIds));
                    }
                    queryBuilder.must(QueryBuilders.termQuery("isOpen", 1));
                }
            }
        }
        return null;
    }

    private QueryBuilder shareQuery(PlanDiagramRequest request) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("sharedUserId", SysUtil.getCurrentUserInfo().getId()));

        List<DiagramShareRecord> shareRecordList = esShareDiagramDao.getListByQuery(queryBuilder);
        if (BinaryUtils.isEmpty(shareRecordList)) {
            return null;
        }

        List<Long> diagramIds =
                shareRecordList.stream().map(DiagramShareRecord::getDiagramId).collect(Collectors.toList());

        queryBuilder = QueryBuilders.boolQuery();
        if (!BinaryUtils.isEmpty(request.getDirType())) {
            TermQueryBuilder dirType = QueryBuilders.termQuery("dirType", request.getDirType());
            queryBuilder.must(dirType);
        }

        if (!BinaryUtils.isEmpty(request.getDiagramName())) {
            MultiMatchQueryBuilder name = QueryBuilders.multiMatchQuery(request.getDiagramName(), "name")
                    .operator(Operator.AND).type(MultiMatchQueryBuilder.Type.PHRASE_PREFIX).lenient(true);
            queryBuilder.must(name);
        }

        TermsQueryBuilder viewTypes = QueryBuilders.termsQuery("viewType.keyword", request.getViewTypes());
        TermsQueryBuilder id = QueryBuilders.termsQuery("id", diagramIds);
        return queryBuilder.must(id).must(viewTypes);
    }

    private List<String> findSysDiagramEnergyList(List<String> sysCiCodeList) {
        if (BinaryUtils.isEmpty(sysCiCodeList)) {
            return Collections.emptyList();
        }

        TermsQueryBuilder condition = QueryBuilders.termsQuery("esSysId", sysCiCodeList);
        BoolQueryBuilder query = QueryBuilders.boolQuery().must(condition);
        List<EamDiagramRelationSys> list = eamDiagramRelationSysDao.getListByQuery(query);
        return BinaryUtils.isEmpty(list) ? null :
                list.stream().map(EamDiagramRelationSys::getDiagramEnergy).collect(Collectors.toList());

    }

    @Override
    public Page<RelateDiagram> queryRelateDiagramList(RelateionDiagramVo params) {
        BinaryUtils.checkNull(params.getLocation(), "视图来源");
        BinaryUtils.checkNull(params.getViewType(), "视图类型");
        if (params.getLocation() == 0) {
            BinaryUtils.checkNull(params.getOwner(), "视图位置");
        }
        BoolQueryBuilder relateDiagramQuery = QueryBuilders.boolQuery();
        relateDiagramQuery.must(QueryBuilders.termQuery("dataStatus", 1));
        relateDiagramQuery.must(QueryBuilders.termQuery("status", 1));
        relateDiagramQuery.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        relateDiagramQuery.must(QueryBuilders.termQuery("domainId", SysUtil.getCurrentUserInfo().getDomainId()));
        relateDiagramQuery.must(QueryBuilders.termQuery("isOpen", params.getLocation()));
        //这块处理一下不查询模板类型的视图
        relateDiagramQuery.must(QueryBuilders.termsQuery("diagramType",Arrays.asList(1,2)));
        //视图名称筛选
        if (StringUtils.hasText(params.getDiagramName())) {
            relateDiagramQuery.must(QueryBuilders.multiMatchQuery(params.getDiagramName(), "name")
                    .operator(Operator.AND).type(MultiMatchQueryBuilder.Type.PHRASE_PREFIX).lenient(true));
        }
        //视图类型筛选
        relateDiagramQuery.must(this.getArtifactRelateDiagramQuery(params));
        relateDiagramQuery.must(params.getLocation() == 0 ?
                this.getPrivateRelateDiagramQuery(params) :
                this.getDesignRelateDiagramQuery(params));

        Page<ESDiagram> page = esDiagramDao.getSortListByQuery(params.getPageNum(), params.getPageSize(), relateDiagramQuery, "createTime", false);
        List<RelateDiagram> relateDiagrams = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page.getData())) {
            List<ESDiagram> diagrams = page.getData();
            Set<Long> userIds = diagrams.stream()
                    .filter(diagram -> diagram.getUserId() != null)
                    .map(ESDiagram::getUserId).collect(Collectors.toSet());
            Map<Long, SysUser> userMap = new ConcurrentHashMap<>();
            if (!CollectionUtils.isEmpty(userIds)) {
                userMap = this.queryUserList(userIds);
            }
            for (ESDiagram diagram : diagrams) {
                if (StringUtils.hasText(diagram.getIcon1())) {
                    diagram.setIcon1(httpResouceUrl + diagram.getIcon1());
                }
                RelateDiagram relateDiagram = new RelateDiagram();
                BeanUtils.copyProperties(diagram, relateDiagram);
                relateDiagram.setUserName(userMap.getOrDefault(diagram.getUserId(), new SysUser()).getUserName());
                relateDiagrams.add(relateDiagram);
            }
        }
        return new Page<>(page.getPageNum(), page.getPageSize(), page.getTotalRows(), page.getTotalPages(), relateDiagrams);
    }

    private BoolQueryBuilder getArtifactRelateDiagramQuery(RelateionDiagramVo relateDiagramQuery) {
        BoolQueryBuilder artifactQuery = QueryBuilders.boolQuery();
        String viewType = relateDiagramQuery.getViewType();
        //全部类型视图
        if (viewType.equals("1")) {
            return artifactQuery;
        }
        //自由视图
        if (viewType.equals("0")) {
            artifactQuery.mustNot(QueryBuilders.existsQuery("viewType"));
            return artifactQuery;
        }
        //制品类型视图
        artifactQuery.must(QueryBuilders.termQuery("viewType.keyword", viewType));
        return artifactQuery;
    }

    private BoolQueryBuilder getPrivateRelateDiagramQuery(RelateionDiagramVo relateDiagramQuery) {
        BoolQueryBuilder privateQuery = QueryBuilders.boolQuery();
        //1-我创建的，2-与我协作，3-全部
        SysUser currentUser = SysUtil.getCurrentUserInfo();
        if (relateDiagramQuery.getOwner() != 1) {
            BoolQueryBuilder shareQueryBuilder = QueryBuilders.boolQuery();
            shareQueryBuilder.must(QueryBuilders.termQuery("sharedUserId", currentUser.getId()));
            List<DiagramShareRecord> shareRecordList = esShareDiagramDao.getListByQuery(shareQueryBuilder);
            if (CollectionUtils.isEmpty(shareRecordList)) {
                //只查与我协作，无结果时查询条件置空
                if (relateDiagramQuery.getOwner() == 2) {
                    privateQuery.must(QueryBuilders.termQuery("id", -1L));
                    return privateQuery;
                }
            } else {
                Set<Long> diagramIds = shareRecordList.stream().map(DiagramShareRecord::getDiagramId).collect(Collectors.toSet());
                privateQuery.should(QueryBuilders.termsQuery("id", diagramIds));
            }
        }
        if (relateDiagramQuery.getOwner() != 2) {
            privateQuery.should(QueryBuilders.termQuery("creator.keyword", currentUser.getLoginCode()));
        }
        return privateQuery;
    }

    private BoolQueryBuilder getDesignRelateDiagramQuery(RelateionDiagramVo relateDiagramQuery) {
        BoolQueryBuilder designQuery = QueryBuilders.boolQuery();
        List<Long> rootIds = new ArrayList<>();
        if (relateDiagramQuery.getLibraryId() == null) {
            //查当前用户所有权限分库
            List<EamCategoryDTO> rootCategories = categorySvc.queryDesignPermissionRootList(SysUtil.getCurrentUserInfo().getLoginCode());
            //无结果时查询条件置空
            if (CollectionUtils.isEmpty(rootCategories)) {
                designQuery.must(QueryBuilders.termQuery("id", -1L));
                return designQuery;
            }
            rootIds.addAll(rootCategories.stream().map(EamCategoryDTO::getId).collect(Collectors.toSet()));
        } else {
            rootIds.add(relateDiagramQuery.getLibraryId());
        }
        //获取权限目录
        List<EamCategory> categories = categorySvc.queryDesignPermissionList(rootIds, SysUtil.getCurrentUserInfo().getLoginCode());
        //无结果时查询条件置空
        if (CollectionUtils.isEmpty(categories)) {
            designQuery.must(QueryBuilders.termQuery("id", -1L));
            return designQuery;
        }
        designQuery.must(QueryBuilders.termsQuery("dirId", categories.stream().map(EamCategory::getId).collect(Collectors.toSet())));
        return designQuery;
    }
}
